<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>仿淘宝固定侧边栏</title>
  <style>
    .slider-bar {
      position: absolute;
      left: 50%;
      top: 300px;
      margin-left: 600px;
      width: 45px;
      height: 130px;
      background-color: pink;
    }

    .w {
      width: 1200px;
      margin: 10px auto;
    }

    .header {
      height: 150px;
      background-color: red;
      line-height: 150px;
      text-align: center;
      font-size: 30px;
    }

    .banner {
      height: 250px;
      background-color: skyblue;
      line-height: 250px;
      text-align: center;
      font-size: 30px;
    }

    .main {
      height: 2000px;
      background-color: yellowgreen;
      line-height: 300px;
      text-align: center;
      font-size: 30px;
    }

    span {
      display: none;
      position: absolute;
      bottom: 0;
    }
    .goBack {
      cursor: pointer;
    }
  </style>
</head>
<body>
  <div class="slider-bar">
    <span class="goBack">返回顶部</span>
  </div>
  <div class="header w">头部区域</div>
  <div class="banner w">banner区域</div>
  <div class="main w">主体部分</div>
  <script>
    //1. 获取元素
    var sliderbar = document.querySelector('.slider-bar')
    var banner = document.querySelector('.banner')
    // banner.offsetTop 就是被卷去头部的大小 一定要写到滚动的外面
    var bannerTop = banner.offsetTop
    // 当我们侧边栏固定定位之后应该变化的数值
    var sliderbarTop = sliderbar.offsetTop - bannerTop
    // 获取main 主体元素
    var main = document.querySelector('.main')
    var goBack = document.querySelector('.goBack')
    var mainTop = main.offsetTop
    // 2. 页面滚动事件 scroll
    document.addEventListener('scroll', function () {
      // console.log(11);
      // window.pageYOffset 页面被卷去的头部      现在都用scrollY
      // console.log(window.pageYOffset)
      // 3 .当我们页面被卷去的头部大于等于了 172 此时 侧边栏就要改为固定定位
      if (window.scrollY >= bannerTop) {
        sliderbar.style.position = 'fixed'
        sliderbar.style.top = sliderbarTop + 'px'
      } else {
        sliderbar.style.position = 'absolute'
        sliderbar.style.top = '300px'
      }
      // 4. 当我们页面滚动到main盒子，就显示 goback模块
      if (window.scrollY >= mainTop) {
        goBack.style.display = 'block'
      } else {
        goBack.style.display = 'none'
      }
    })
    goBack.addEventListener('click', function () {
      window.scrollTo({
        top: 0,
        behavior: 'smooth',
      })
    })
  </script>
</body>
</html>